import GoodsTable from '@/pages/Goods/components/GoodsTable'
import GoodsUpdateModal from '@/pages/Goods/components/GoodsUpdateModal'
import { GoodsUpdateDTO, GoodsVO, saveGoods, updateGoods } from '@/services/GoodsService'
import { PageContainer } from '@ant-design/pro-components'
import { ActionType } from '@ant-design/pro-table'
import { message } from 'antd'
import { useRef, useState } from 'react'

const Goods = () => {
  // 编辑操作
  const [updateModalState, setUpdateModalState] = useState(false)
  const [currentGoods, setCurrentGoods] = useState<GoodsVO | undefined>()
  // 表格引用
  const tableRef = useRef<ActionType>()
  const updateEvent = async (record: GoodsVO) => {
    // 打开模态框
    setCurrentGoods(record)
    setUpdateModalState(true)
  }

  const saveEvent = async () => {
    // 打开模态框
    setUpdateModalState(true)
  }

  const onUpdateModalChange = async (state: boolean) => {
    if (state) {
      setUpdateModalState(state)
    } else {
      await setCurrentGoods(undefined)
      setUpdateModalState(state)
    }
  }
  // 提交修改
  const onUpdateFinish = async (formData: any) => {
    let dto: GoodsUpdateDTO = JSON.parse(JSON.stringify(formData))
    let response
    if (currentGoods) {
      response = await updateGoods(dto)
    } else {
      response = await saveGoods(dto)
    }
    if (response) {
      message.success('操作成功')
      // 刷新表格
      tableRef.current?.reload()
      return true
    }
    return false
  }

  return (
    <PageContainer title="套系">
      {/*套系表格 开始*/}
      <GoodsTable tableRef={tableRef} onSave={saveEvent} onUpdate={updateEvent} />
      {/*套系表格 结束*/}

      {/*修改模态框 开始*/}
      <GoodsUpdateModal
        goods={currentGoods}
        open={updateModalState}
        onOpenChange={onUpdateModalChange}
        onFinish={onUpdateFinish}
      />
      {/*修改模态框 结束*/}
    </PageContainer>
  )
}

export default Goods
